/*
 * $HeadURL:  $
 *
 * Copyright (c) 2007 Drutt Corporation, all rights reserved.
 *
 */
package homework.james.xiao.server;

import homework.james.xiao.bean.Admin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

/**
 * @author eyngxao
 * @version $Revision: $
 */
public class AdminServer implements Runnable {

	/** Class revision */
	public static final String _REV_ID_ = "$Revision: $";
	private ServerSocket adminSocket;
	private ExecutorService executorService;
	/**
	 * @param adminSocket
	 */
	public AdminServer(ServerSocket adminSocket,ExecutorService executorService) {
		this.adminSocket = adminSocket;
		this.executorService = executorService;
	}
	private BufferedReader getReader(Socket socket) throws IOException{
        InputStream socketIn=socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketIn,"UTF-8"));
    }
    private ObjectOutputStream getObjectOutputStream(Socket socket) throws IOException{
        OutputStream socketOut=socket.getOutputStream();
        return new ObjectOutputStream(socketOut);
    }
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void run() {
		Socket socket = null;
		try {
			// 接收客户连接
			socket = adminSocket.accept();
			System.out.println("New connection accepted "
					+ socket.getInetAddress() + ":" + socket.getPort());
			BufferedReader br = getReader(socket);
			ObjectOutputStream oos = getObjectOutputStream(socket);
			Admin admin = new Admin(oos);
			String command = "";
			while (true) {
				System.out.println("AdminServer: waiting for command from client");
				command = br.readLine(); // 读入从client传来的字符串
				System.out.println("command recevied: " + command);
				int result = admin.handle(command);
				if(result == Admin.EXIT)
						break;
				if (result == Admin.SHUTDOWN){
						shutdownServer();
						break;
				}
			}			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
	private void shutdownServer() throws IOException {
		System.out.println("Server is shutting down, buy");
		executorService.shutdown(); 		
		System.out.println("Server is successfull shutdown");
		System.out.println(executorService.isShutdown());
	}
}
